<template>
    <view class="page">
        <view class="list-item" v-for="(item, index) in users" :key="index" @click="connect(item)">
            <view class="avatar">
                <text class="round" v-if="getUnreadMessageCount(item) > 0">
                    {{ getUnreadMessageCount(item) }}
                </text>
                <image :src="item.userAvatar" mode="widthFix"></image>
            </view>
            <view class="content">
                <view class="title">
                    <text class="name">{{ item.userNickname }}</text>
                    <text class="time">{{ formatTime(item.lastMessageTime) }}</text>
                </view>
                <view class="txt">{{ item.lastMessageContent }}</view>
            </view>
        </view>
        <!-- 底部导航 -->
        <BottomNav currentPage="chatList" />
    </view>
</template>

<script>
import cfg from '@/common/config.js'
    import BottomNav from "./../components/BottomNav.vue";

    export default {
        components: {
            BottomNav
        },
        data() {
            return {
                websocketPath: '', // WebSocket 路径
                users: [],  // 数据初始化为空数组
                currentUserId: null, // 假设当前用户 ID
                enable: false
            };
        },
        mounted() {
            this.enable = this.f.storage('switchCfg').module.enable
            this.currentUserId = this.f.storage('user_data').userId
            this.loadList();
            this.websocketPath = cfg.url.replace('http','ws') + '/infra/ws' + '?token=' + this.token;
            console.log('WebSocket 地址:',this.websocketPath);
            // 连接 WebSocket
            this.connectWebSocket();
        },
        methods: {
            // 连接 WebSocket
            connectWebSocket() {
                uni.connectSocket({
                    url: this.websocketPath, // WebSocket 地址
                });

                uni.onSocketOpen(() => {
                    console.log('WebSocket 连接成功');
                    this.loadList();
                });

                uni.onSocketMessage(() => {
                    this.loadList();
                });

                uni.onSocketError((error) => {
                    console.error('WebSocket 错误:',error);
                });

                uni.onSocketClose(() => {
                    console.log('WebSocket 连接已关闭');
                });
            },
            loadList() {
                this.users = [];
                this.$api.req(`/promotion/kefu-conversation/list`,{},'GET',"JSON",false).then(res => {
                    if (res.code === 0 && this.enable) {
                        this.users = res.data.map(item => ({
                            id: item.id,
                            opsUserId: item.opsUserId,
                            userId: item.userId,
                            userAvatar: item.userAvatar,
                            userNickname: item.userNickname,
                            lastMessageTime: item.lastMessageTime,
                            lastMessageContent: item.lastMessageContent,
                            adminUnreadMessageCount: item.adminUnreadMessageCount,
                            userIdUnreadMessageCount: item.userIdUnreadMessageCount,
                            opsUserIdUnreadMessageCount: item.opsUserIdUnreadMessageCount
                        }));
                    }
                });
            },
            connect(item) {
                var t = this
                t.$api.req(`/promotion/kefu-message/update-chat-read-status?conversationId=${item.id}`,{ 'conversationId': item.id },'POST',"JSON",false).then(res => {
                    if (res.code === 0) {
                        uni.navigateTo({
                            url: `/subPackage1/chat/chat?name=${item.userNickname}&avatar=${item.userAvatar}&userId=${item.opsUserId}`
                        });
                    }
                });

            },
            formatTime(timestamp) {
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2,'0');
                const day = String(date.getDate()).padStart(2,'0');
                const hour = String(date.getHours()).padStart(2,'0');
                const minute = String(date.getMinutes()).padStart(2,'0');
                return `${year}/${month}/${day} ${hour}:${minute}`;
            },
            getUnreadMessageCount(item) {
                if (this.currentUserId === item.userId) {
                    return item.userIdUnreadMessageCount;
                } else {
                    return item.opsUserIdUnreadMessageCount;
                }
            }
        }
    };
</script>

<style lang="scss" scoped>
    .page {
        padding: 0 32rpx;
        color: #333;
    }

    .list-item {
        display: flex;
        padding: 30rpx 0;
        border-bottom: 1px solid #f7f8f9;

        .avatar {
            width: 90rpx;
            height: 90rpx;
            border-radius: 10rpx;
            margin-right: 20rpx;
            position: relative;

            .round {
                position: absolute;
                width: 14rpx;
                height: 14rpx;
                border-radius: 50%;
                background: #ef5656;
                top: -4rpx;
                right: -4rpx;
                z-index: 1;
                display: flex;
                justify-content: center;
                align-items: center;
                color: white;
                font-size: 20rpx;
            }

            image {
                width: 100%;
                height: 100%;
                border-radius: 10rpx;
            }
        }

        .content {
            flex: 1;

            .title {
                display: flex;
                justify-content: space-between;

                .name {
                    font-weight: bold;
                }

                .time {
                    color: #999;
                    font-size: 24rpx;
                }
            }

            .txt {
                margin-top: 10rpx;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                text-align: left;
                color: #999;
                font-size: 26rpx;
            }
        }
    }
</style>